/**
 * iSocial Project
 * http://isocial.missouri.edu
 *
 * Copyright (c) 2011, University of Missouri iSocial Project, All Rights Reserved
 *
 * Redistributions in source code form must reproduce the above
 * copyright and this condition.
 *
 * The contents of this file are subject to the GNU General Public
 * License, Version 2 (the "License"); you may not use this file
 * except in compliance with the License. A copy of the License is
 * available at http://www.opensource.org/licenses/gpl-license.php.
 *
 * The iSocial project designates this particular file as
 * subject to the "Classpath" exception as provided by the iSocial
 * project in the License file that accompanied this code.
 */
package org.jdesktop.wonderland.modules.isocial.generic.client;

import java.awt.CardLayout;
import java.awt.Component;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jdesktop.wonderland.modules.isocial.client.ISocialManager;
import org.jdesktop.wonderland.modules.isocial.common.model.Result;
import org.jdesktop.wonderland.modules.isocial.common.model.Sheet;
import org.jdesktop.wonderland.modules.isocial.generic.common.GenericAnswer;
import org.jdesktop.wonderland.modules.isocial.generic.common.GenericResult;
import org.jdesktop.wonderland.modules.isocial.generic.common.GenericSheet;

/*
 * This class may not be needed, but let's leave it here for legacy support
 * just in case.
 *
 * -Ryan
 */
/**
 * Panel for viewing a sample
 * @author Jonathan Kaplan <jonathankap@wonderbuilders.com>
 * @author Kaustubh
 */
public class GenericSheetViewPanel extends javax.swing.JPanel {

    private static final Logger LOGGER =
            Logger.getLogger(GenericSheetViewPanel.class.getName());
    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(
            "org/jdesktop/wonderland/modules/isocial/generic/client/Bundle");
    private final ISocialManager manager;
    private final Sheet sheet;
    private int panelCount = 0;
    private int qCount = 0;

    public GenericSheetViewPanel(ISocialManager manager, Sheet sheet) {
        this.manager = manager;
        this.sheet = sheet;
        initComponents();
        String directions = ((GenericSheet) sheet.getDetails()).getDirections();

        //if the sheet direction are not defined, hide the scrollpane.
        if (directions.length() < 1) {
            jScrollPane1.setVisible(false);
        } else {
            jTextArea1.setText(directions);
        }
        backButton.setEnabled(false);
        submitButton.setEnabled(false);
    }

    /**
     * Set the view with the given result. This will disable the submit
     * button and fill in results from the given result.
     * @param result the result to set this sheet from
     */
    public void setResult(Result result) {
        setReviewVisible(result);
        submitButton.setEnabled(false);
    }

    /**
     * Get a ResultDetails object from this view.
     * @return a SampleResultDetails object filled in with the details from this
     * view
     */
    public GenericResult getResultDetails() {
        GenericResult details = new GenericResult();
        details.setAnswers(getResultsFromReviewPanel());
        return details;
    }

    /**
     * Toggle this panel editable
     */
    public void setEditable(boolean editable) {
        //answerArea.setEditable(editable);
        submitButton.setEnabled(editable);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        leftPanel = new javax.swing.JPanel();
        cardPanel = new javax.swing.JPanel();
        buttonPanel = new javax.swing.JPanel();
        backButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        submitButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setSize(new java.awt.Dimension(500, 450));
        setLayout(new java.awt.GridLayout(1, 0));

        jSplitPane1.setDividerLocation(400);

        leftPanel.setLayout(new java.awt.BorderLayout());

        cardPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cardPanel.setLayout(new java.awt.CardLayout());
        leftPanel.add(cardPanel, java.awt.BorderLayout.CENTER);

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/isocial/generic/client/Bundle"); // NOI18N
        backButton.setText(bundle.getString("GenericSheetViewPanel.backButton.text")); // NOI18N
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(backButton);

        nextButton.setText(bundle.getString("GenericSheetViewPanel.nextButton.text")); // NOI18N
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(nextButton);

        submitButton.setText(bundle.getString("GenericSheetViewPanel.submitButton.text")); // NOI18N
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(submitButton);

        leftPanel.add(buttonPanel, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setLeftComponent(leftPanel);

        jTextArea1.setColumns(10);
        jTextArea1.setEditable(false);
        jTextArea1.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setBounds(new java.awt.Rectangle(0, 0, 150, 80));
        jTextArea1.setMinimumSize(new java.awt.Dimension(150, 16));
        jScrollPane1.setViewportView(jTextArea1);

        jSplitPane1.setRightComponent(jScrollPane1);

        add(jSplitPane1);
    }// </editor-fold>//GEN-END:initComponents

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
        String title = "Submit " + sheet.getName();
        String message = "Are you sure you want to submit the sheet " + sheet.getName();
        int confirm = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            firePropertyChange("submit", null, "");
        }
    }//GEN-LAST:event_submitButtonActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        updateAnswer();
        CardLayout layout = (CardLayout) cardPanel.getLayout();
        layout.previous(cardPanel);
        updateButtonState();
    }//GEN-LAST:event_backButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        updateAnswer();
        CardLayout layout = (CardLayout) cardPanel.getLayout();
        layout.next(cardPanel);
        updateButtonState();
    }//GEN-LAST:event_nextButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JPanel cardPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JPanel leftPanel;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton submitButton;
    // End of variables declaration//GEN-END:variables

    /**
     * This method adds all the cards in the wizard. Each card is used for one
     * question.
     * @param allQPanels
     */
    void addCards(List<JPanel> allQPanels) {
        int i = 1;
        for (Iterator<JPanel> it = allQPanels.iterator(); it.hasNext();) {
            JPanel jPanel = it.next();
            cardPanel.add(jPanel, "card" + i);
            i++;
        }
    }

    /**
     * This method updates the answers in the review panel every time Back /
     * Next button is pressed.
     */
    private void updateAnswer() {
        Component[] components = cardPanel.getComponents();
        int i = 0;
        int j = components.length;
        while (i < j) {
            if (components[i].isVisible()) {
                String answer = "";
                ReviewPanel review = (ReviewPanel) components[j - 1];
                if (components[i] instanceof MCQExclusivePanel) {
                    MCQExclusivePanel panel = (MCQExclusivePanel) components[i];
                    answer = panel.getSelectedAnswers();
                    review.updateAnswer(answer, i);
                } else if (components[i] instanceof MCQInclusivePanel) {
                    MCQInclusivePanel panel = (MCQInclusivePanel) components[i];
                    answer = panel.getSelectedAnswers();
                    review.updateAnswer(answer, i);
                } else if (components[i] instanceof OEQPanel) {
                    OEQPanel panel = (OEQPanel) components[i];
                    answer = panel.getSelectedAnswers();
                    review.updateAnswer(answer, i);
                }
                break;
            } else {
                i++;
            }
        }
    }

    /**
     * This method retrieves the List of GenericAnswer from the review panel
     * table.
     * @return
     */
    private List<GenericAnswer> getResultsFromReviewPanel() {
        Component[] components = cardPanel.getComponents();
        ReviewPanel review = (ReviewPanel) components[components.length - 1];
        return review.getAnswerList();
    }

    /**
     * This method updates the back / next button states.
     * @param jButton
     */
    private void updateButtonState() {

        Component[] components = cardPanel.getComponents();
        int i = 0;
        int j = components.length;
        if (components[0].isVisible()) {
            backButton.setEnabled(false);
            nextButton.setEnabled(true);
            submitButton.setEnabled(false);
        } else if (components[j - 1].isVisible()) {
            nextButton.setEnabled(false);
            backButton.setEnabled(true);
            submitButton.setEnabled(true);
        } else {
            nextButton.setEnabled(true);
            backButton.setEnabled(true);
            submitButton.setEnabled(false);
        }
    }

    void setReviewVisible(Result result) {
        //once the answers are submitted, hide the directions scroll pane
        //jScrollPane1.setVisible(false);
        Component[] components = cardPanel.getComponents();
        int length = components.length;
        ReviewPanel review = (ReviewPanel) components[length - 1];
        GenericResult details = (GenericResult) result.getDetails();
        List<GenericAnswer> answers = details.getAnswers();
        int i = 0;
        for (Iterator<GenericAnswer> it = answers.iterator(); it.hasNext();) {
            GenericAnswer answer = it.next();
            review.updateAnswer(answer.getValue(), i++);
        }
        CardLayout layout = (CardLayout) cardPanel.getLayout();
        layout.last(cardPanel);
        backButton.setEnabled(false);
        nextButton.setEnabled(false);
    }
}
